import datepicker from 'vue-datepicker'
import { modal } from 'vue-strap'
import extend from 'extend'
import getDatePickerOption from '../../../util/date-picker-option'
import { updateAd, showMsg } from '../../../vuex/action'

export default {
  name: 'GaoUpdate',
  props: ['ad', 'position'],
  components: {
    'vue-modal': modal,
    'vue-datepicker': datepicker
  },
  data() {
    return {
      modalStatus: false,
      datePickerOption: getDatePickerOption(),
    }
  },
  computed: {
    isShowTime() {
      // 首页顶部广告和交易TAB广告需要增加生效时间
      return this.position === 7 || this.position === 1
    }
  },
  vuex: {
    actions: {
      xUpdateAd: updateAd,
      xShowMsg: showMsg
    }
  },
  methods: {
    validAd(data) {
      for (let name in data) {
        if ((data[name] + '').length === 0) {
          return '* 标记的均为必填/必选项'
        }
        if (name === 'type' && data[name] < 0) {
          return '* 标记的均为必填/必选项'
        }
        if (['startTime', 'endTime'].indexOf(name) >= 0) {
          if (new Date(data.endTime) <= new Date(data.startTime)) {
            return '结束时间必须晚于开始时间'
          }
        }
      }
    },
    showModal() {
      this.modalStatus = true
    },
    submit() {
      var formData = new FormData()
      var ad = extend(true, {}, this.ad)
      if (!this.isShowTime) {
        delete ad.startTime
        delete ad.endTime
      }

      var errorMsg = this.validAd(ad)
      if (errorMsg) {
        return this.xShowMsg({
          type: 'danger',
          content: errorMsg
        })
      }

      ad.type = +ad.type
      ad.forceExternalBrowser = +ad.forceExternalBrowser
      ad.position = this.position
      for (let name in ad) {
        if (name !== 'file') {
          formData.append(name, ad[name])
        }
      }
      formData.append('file', this.$els.file.files[0])
      this.xUpdateAd(formData)
        .then(() => {
          this.modalStatus = false
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  }
}
